# -*- coding: utf-8 -*-
"""
-------------------------------
   File Name：     skin_auto_update
   Description :   
   Author :        HU
   date：          2021/3/8
-------------------------------
   Change Activity:
                   2021/3/8:
-------------------------------
"""

import requests
from lxml import etree
import re, os, zipfile, time

usr_agent = {
    'User - Agen': 'Mozilla / 5.0(Windows NT 10.0;Win64;x64) AppleWebKit / 537.36(KHTML, likeGecko) Chrome / 86.0.4240.198Safari / 537.36Edg / 86.0.622.69'
}


def get_edittion(url):
    """
    获取下载地址  http://s3.modskinlolvn.com/ModSkin_11.5.1.zip
    return: download_edittion_url
    """
    response = requests.get(url, headers=usr_agent)
    content = response.content.decode('utf-8')
    tree = etree.HTML(content)
    download_edittion_url = tree.xpath('//a[@id="link_download3"]/@href')[0]
    print(f"文件下载地址:{download_edittion_url}\n"
          f"(下载速度慢时可手动复制到浏览器下载)\n")
    return download_edittion_url


def contrast_eddittion(download_edittion_url):
    """
    对比版本号
    """
    global old_edittion
    new_edittion = download_edittion_url[35:-4]  # 11.5.1
    # print(type(new_edittion))  # str
    listdir = os.listdir(
        './')  # ['Data.lol', 'LOLPRO 11.5.1.exe', 'ModSkin_11.5.1.zip', 'README.txt', 'skin_auto_update.py']
    for item in listdir:
        old_edittion = re.match(r"LOLPRO.+", item)
        if old_edittion is not None:  # 如果匹配到了ModSkin_11.5.1.zip
            if new_edittion == old_edittion.group()[7:-4]:
                print("已经是最新版本,无需下载新版本...")
                os.startfile(old_edittion.group())
            elif new_edittion > old_edittion.group()[7:-4]:
                print("发现新版本,开始下载新版本...")
                download(download_edittion_url, new_edittion + '.zip')
                os.remove(old_edittion.group())
                os.startfile('LOLPRO ' + new_edittion + '.exe')
            time.sleep(1)
            return
    if old_edittion is None:
        print("没有下载任何版本LOLSkin,开始下载新版本...")
        download(download_edittion_url, new_edittion + '.zip')
        os.startfile('LOLPRO ' + new_edittion + '.exe')
    time.sleep(2)
    return


def auto_del():
    """删除除了删除列表(not_del_dir),和以LOLPRO,skin开头之外的文件"""
    dirlist = os.listdir('./')
    not_del_dir = ['Data.lol', 'README.txt', ]
    for item in dirlist:
        skin_softwares = re.match(r"skin.+", item)
        old_edittion = re.match(r"LOLPRO.+", item)
        if old_edittion is not None:
            not_del_dir.append(old_edittion.group())
        if skin_softwares is not None:
            not_del_dir.append(skin_softwares.group())
    for item in dirlist:
        if item not in not_del_dir:
            try:
                os.remove(item)
            except Exception as res:
                pass


def unzip(filename):
    """解压文件"""
    print(f'开始解压{filename}....')
    f = zipfile.ZipFile(filename, 'r')
    for file in f.namelist():
        # 解压的文件和路径
        f.extract(file, "./")
    print(f'{filename}解压完成....')
    f.close()
    os.remove(filename)


def download(download_url, filename):
    """下载文件"""
    # 开始时间
    start = time.time()
    size = 0
    response = requests.get(download_url, stream=True, headers={'Proxy-Connection': 'keep-alive'})
    # 每次下载的数据大小
    chunk_size = 128
    content_size = int(response.headers['content-length'])
    # print(content_size)
    if response.status_code == 200:
        # 换算单位并print
        print(f"[{filename}大小:] %0.2f MB" % (content_size / (chunk_size * 1024 * 8)))
        with open(filename, 'wb') as file:
            for data in response.iter_content(chunk_size=chunk_size):
                file.write(data)
                # 已下载文件大小
                size += len(data)
                # \r指定行第一个字符开始 ,搭配end属性覆盖进度条
                print(
                    '\r' + '[下载进度:]%s %.2f%%' % (
                        ('▋' * int(size * 50 / content_size)), (float(size / content_size * 100))),
                    end='')
    end = time.time()
    print('\n'f"{filename}全部下载完成,用时%.2f秒" % (end - start))
    unzip(filename)


if __name__ == '__main__':
    auto_del()
    download_edittion_url = get_edittion("http://leagueskin.net/p/download-mod-skin-2020-chn")
    contrast_eddittion(download_edittion_url)
